package com.feinno.module.security.service.impl;

import java.util.Date;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.feinno.framework.common.dao.support.PageInfo;
import com.feinno.framework.common.exception.BusinessException;
import com.feinno.framework.common.service.EntityServiceImpl;
import com.feinno.framework.utils.Dates;
import com.feinno.module.security.dao.ResourceDao;
import com.feinno.module.security.domain.Resource;
import com.feinno.module.security.service.ResourceService;
import com.feinno.module.security.shiro.realm.ShiroDbRealm;
import com.google.common.collect.Maps;

@Service("resourceService")
public class ResourceServiceImpl extends
		EntityServiceImpl<Resource, ResourceDao> implements ResourceService {

	@Autowired
	private ShiroDbRealm shiroDbRealm;

	@Override
	public void save(Resource o) throws BusinessException {
		super.save(o);
		try {
			// 清空权限缓存
			shiroDbRealm.clearCachedAuthorizationInfo(SecurityUtils
					.getSubject().getPrincipals());
		} catch (Exception e) {
			// ig
		}

	}

	@Override
	public Resource findByResString(String url) {
		return getEntityDao().findByResString(url);
	}

	@Override
	public void moveUp(Long id) {
		try {
			Resource resource = get(id);
			Date current = resource.getOrderTime();
			Resource perv = null;

			long count = getEntityDao().getCountByGtOrderTime(current);
			if (count > 0) {
				PageInfo<Resource> pageInfo = new PageInfo<Resource>(1,
						(int) count);
				Map<String, Boolean> sortMap = Maps.newLinkedHashMap();
				sortMap.put("menu.orderTime", false);
				sortMap.put("orderTime", false);
				Map<String, Object> searchMap = Maps.newHashMap();
				searchMap.put("GT_orderTime", Dates.format(current,
						Dates.CHINESE_DATETIME_FORMAT_LINE));
				pageInfo = getEntityDao().query(pageInfo, searchMap, sortMap);
				if (pageInfo.getPageResults() != null
						&& pageInfo.getPageResults().size() > 0) {
					perv = pageInfo.getPageResults().get(0);
				}
			}

			if (perv != null) {
				resource.setOrderTime(perv.getOrderTime());
				perv.setOrderTime(current);
				save(perv);
			} else {
				resource.setOrderTime(new Date());
			}
			save(resource);
		} catch (Exception e) {
			throw new BusinessException("上移失败", e);
		}

	}

	@Override
	public void moveTop(Long id) {
		try {
			Resource resource = get(id);
			resource.setOrderTime(new Date());
			save(resource);
		} catch (Exception e) {
			throw new BusinessException("置顶失败", e);
		}
	}

}
